#include <workflow/WFTaskFactory.h>
#include <workflow/RedisMessage.h>
#include <workflow/WFFacilities.h>
#include <iostream>

void redis_auth_callback(WFRedisTask *task) {
    protocol::RedisResponse *resp = task->get_resp();
    int state = task->get_state();
    int error = task->get_error();

    if (state == WFT_STATE_SUCCESS) {
        protocol::RedisValue val;
        resp->get_result(val);

        if (val.is_error()) {
            std::cerr << "Authentication failed: " << val.string_value() << std::endl;
        } else {
            std::cout << "Authentication succeeded." << std::endl;
        }
    } else {
        std::cerr << "Task error: state=" << state << " error=" << error << std::endl;
    }
}


void redis_command_callback(WFRedisTask *task) {
    protocol::RedisResponse *resp = task->get_resp();
    int state = task->get_state();
    int error = task->get_error();

    if (state == WFT_STATE_SUCCESS) {
        protocol::RedisValue val;
        resp->get_result(val);

        if (val.is_string()) {
            std::cout << "Response: " << val.string_value() << std::endl;
        } else {
            std::cout << "Unexpected response type." << std::endl;
        }
    } else {
        std::cerr << "Task error: state=" << state << " error=" << error << std::endl;
    }
}

int main() {
    WFFacilities::WaitGroup wait_group(1);

    std::string url = "*";

    WFRedisTask *auth_task = WFTaskFactory::create_redis_task(url, 3, redis_auth_callback);
    auth_task->get_req()->set_request("ping", {});

    WFRedisTask *command_task = WFTaskFactory::create_redis_task(url, 3, redis_command_callback);
    command_task->get_req()->set_request("get", {"杨磊"});

    auth_task->set_callback([&wait_group, command_task](WFRedisTask *task) {
        if (task->get_state() == WFT_STATE_SUCCESS) {
            series_of(task)->push_back(command_task);
        } else {
            wait_group.done();
        }
    });

    auth_task->start();
    wait_group.wait();

    return 0;
}
